<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class PersonCheck extends CI_Controller{
    private $appId;
    private $appSecret;
    
    function __construct() {
        parent::__construct();
        $this->appId = "wx48ac7010d65a20d7";
        $this->appSecret = "yWmfWG4nIkjatVdWuWdgqEk1NhjipzzTW6xHVhODYe2FdE6Q3XkoY2aEy53ShZCi";
        $this->load->library('PersonCheck');
    }
    public function index($userid,$username){
    /*
    public function index(){
        $userid = "6522";
        $username = "张雪林";
        */
        header("Access-Control-Allow-Origin:*");
        $res['userid']    = $userid;
        $res['username']  = $username;
        $res['type']      = "add";
        $this->load->view("PersonCheck",$res);
    }
    
    public function addData(){
        header("Access-Control-Allow-Origin:*");
        $userid        = $_REQUEST['userid'];
        $username      = $_REQUEST['username'];
        $leavetype     = $_REQUEST['leavetype'];
        $remark        = $_REQUEST['remark'];
        $departuretime = $_REQUEST['departuretime'];
        $backtime      = $_REQUEST['backtime'];
        date_default_timezone_set('Asia/Shanghai'); 
        $createtime    = date("Y-m-d H:i:s",time());
        $this->Data_model->add_data_Oracle(array("USERID" => $userid,
                                            "USERNAME" => $username,
                                            "LEAVETYPE" => $leavetype,
                                            "REMARK" => $remark,
                                            "DEPARTURETIME" => $departuretime,
                                            "BACKTIME" => $backtime,
                                            "CREATETIME" => $createtime),"PERSONORDER");
    }
    
    function editData_show($id){
        $data = $this->Data_model->get_single_data("ID = ".$id,"PERSONORDER");
        $res['data'] = $data;
        $res['type'] = "edit";
        var_dump("edit");
        var_dump($res);
        $this->load->view("PersonCheck",$res);
    }
    
    function showData($id){
        $data = $this->Data_model->get_single_data("ID = ".$id,"PERSONORDER");
        $res['data'] = $data;
        $res['type'] = "show";
        $this->load->view("PersonCheck",$res);
    }
    
    public function judgeUser(){
        header("Access-Control-Allow-Origin:*");
        $id       = $_REQUEST["ID"];
        $Uid      = $_REQUEST["Uid"];  //微信中带过来的当前用户ID
        $res = $this->Data_model->get_single_data("ID = ".$id,"PERSONORDER");
        /*
         * 判断当前用户是否能够修改请假信息
        if($Uid == $res['USERID']){
            $this->editData_show($id);
        }else{
            $this->showData($id);
        }
         * 
         */
        $this->showData($id);
    }

    public function getOutList($userid){
        header("Access-Control-Allow-Origin:*");
        date_default_timezone_set('Asia/Shanghai'); 
        $date = date("Y-m-d H:i:s",  time());
        $where = array("DEPARTURETIME <=" => $date,
                        "BACKTIME >=" => $date);
        $res = $this->Data_model->get_data($where,"","ID desc",0,0,"PERSONORDER");
        $return['data'] = $res;
        $return['type'] = "list";
        $return['Uid'] = $userid;
        $this->load->view("PersonCheck",$return);
    }
    
    public function Login_List(){
        if (isset($_GET['code'])){
            $code = $_GET['code'];
            $res = $this->Data_model->get_single_data(array('name'=>'中骏森驰',
                                                            'type'=>'PersonCheck_2'),"WEIXININFOZJ");
            $this->get_userId($res['access_token'], $code,$res['agentid'],$type = 'list');
            
        }else{
            echo "NO CODE";
        }
    }

    public function Login(){
        if (isset($_GET['code'])){
            $code = $_GET['code'];
            $res = $this->Data_model->get_single_data(array('name'=>'中骏森驰',
                                                            'type'=>'PersonCheck_2'),"WEIXININFOZJ");
            $this->get_userId($res['access_token'], $code,$res['agentid'],$type = 'add');
            
        }else{
            echo "NO CODE";
        }
    }
    
    /*
     * 根据UserId获取用户信息
     */
    function get_userInfo($userId,$access_token,$type){
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."&userid=".$userId;
        $json=self::http_request_json($url);//这个地方不能用file_get_contents
        $data=json_decode($json,true);
        if ($type == "add"){
            $this->index($data['userid'],$data['name']);
        }elseif($type == "list"){
            $this->getOutList($data['userid']);
        }
        
    }
    
    function get_userId($access_token,$code,$agentId,$type){
        if($access_token){
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$access_token."&code=".$code."&agentid=".$agentId;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data['errcode'])){
                if($data['errcode'] == "40001" or $data['errcode'] == '42001' or $data['errcode'] == '40014'){
                    $this->get_access_token();
                    $newurl = "http://weixin.gensenauto.com/WEIXIN/PersonCheck/Login?code=".$code;  
                    echo "<script language='javascript' type='text/javascript'>";  
                    echo "window.location.href='".$newurl."'";  
                    echo "</script>"; 
                    
                }else{
                    echo "页面请求错误，请检查！";
                }
            }else{
                $this->get_userInfo($data['UserId'],$access_token,$type);
            }
        }else{
            $this->get_access_token();
            $this->Login();
        }
    }
    function get_access_token(){
        $result = $this->Data_model->get_single_data(array('name'=>'中骏森驰',
                                                            'type'=>'PersonCheck_2'),"WEIXININFOZJ");
        if($result['time'] < time()){
            $corpid = $result['corpid'];
            $corpsecret = $result['corpsecret'];
            $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data['access_token'])){
                $this->Data_model->update_data(array('name'=>'中骏森驰',
                                                                'type'=>'PersonCheck_2'),array('access_token' => $data['access_token'],'time' => time()+7100),'WEIXININFOZJ');
            
                $access_token = $data['access_token'];
            }else{
                return "获取access_token错误";
            } 
        }else{
            $access_token = $result['access_token'];
        }
        return $access_token;
    }
    //因为url是https 所有请求不能用file_get_contents,用curl请求json 数据
    function http_request_json($url){  
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;  
    }
}
